package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;
import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;
import model.DatabaseException;

/**
 * Servlet implementation class CategoryServlet
 */
@WebServlet("/CategoryJSON")
public class CategoryJSON extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CategoryJSON() {
        super();
        // TODO Auto-generated constructor stub
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> parameters = request.getParameterMap();
		String[] sizes=parameters.getOrDefault("sizeIds[]", null);

		String[] colors = parameters.getOrDefault("colorIds[]", null);
	
		String minPrice = request.getParameter("minPrice");
		String maxPrice = request.getParameter("maxPrice");
		String minCount = request.getParameter("minCount");
//		String maxCount= request.getParameter("maxCount");
//		System.out.println(minPrice);
//		System.out.println(maxPrice);
		String categoryName = new String(request.getParameter("categoryName").getBytes(
                "iso-8859-1"), "UTF-8");
//		response.setContentType("application/json");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
	
		try {
			Optional<Category> categoryOptional = Category.getCategory(categoryName,colors,sizes,minPrice,maxPrice, minCount, null, null);
			if(categoryOptional.isPresent()){
				Category category = categoryOptional.get();
				String stats = Category.getCategoryJSON(category);
				out.print(stats);
			}
			else{
//				System.out.println("no such thing");
				out.print("{}");
			}
			
		} catch (DatabaseException e) {
//			System.out.println("DB exception");
			out.print("{}");
		}

	}

}
